package com.noahplat.erp.service.impl;

import com.ctc.wstx.sw.EncodingXmlWriter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.erp.mapper.AlterMapper;
import com.noahplat.erp.pojo.AccountAlter;
import com.noahplat.erp.service.AlterService;
import com.noahplat.person.feign.PersonFeign;
import com.noahplat.user.feign.AccountFeign;
import com.noahplat.user.feign.UserFeign;
import com.noahplat.user.pojo.Account;
import com.noahplat.user.pojo.User;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 账套变更审核接口实现
 *
 * @author 李东
 * @version 1.0.0
 * @Date: 2021/3/1 9:13
 **/

@Service
public class AlterServiceImpl implements AlterService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private AlterMapper alterMapper;

    @Autowired
    private PersonFeign personFeign;

    /**
     * 申请变更记录
     *
     * @param acctid
     * @param alterType
     * @return
     */
    @GlobalTransactional
    @Override
    public Result applyAlterInfo(String acctid, String alterType, Long uid) {
        //获取用户信息
        Result<User> userResult = userFeign.findUserById(uid);
        User user = userResult.getData();
        if (ObjectUtils.isEmpty(user) || "Y".equals(user.getDel())) {
            return new Result(true, StatusCode.ACCESSERROR, "当前账户不存在或已注销，申请失败！");
        }
        //查询账套信息
        Result<Account> accountResult = accountFeign.findAccInfoById(Long.parseLong(acctid));
        Account account = accountResult.getData();
        if (ObjectUtils.isEmpty(account) || "N".equals(account.getStatus())) {
            return new Result(true, StatusCode.ACCESSERROR, "当前账套不存在或已失效，申请失败！");
        }
        if (user.getAcctid().toString().equals(acctid)) {
            return new Result(true, StatusCode.REPERROR, "当前已变更当前角色，请勿重复变更！");
        }
        //新增记录
        AccountAlter accountAlter = new AccountAlter();
        accountAlter.setAcctId(Long.parseLong(acctid));
        accountAlter.setAlterType(alterType);
        accountAlter.setStatus("0");
        accountAlter.setAlterDate(new Date());
        accountAlter.setUid(user.getId());
        int i = alterMapper.insertSelective(accountAlter);
        if (i == 0) {
            return new Result(true, StatusCode.SERVER_EXCEPTION, "服务器异常！");
        }
        return new Result(true, StatusCode.OK, "申请成功，等待审核中...");
    }

    @Override
    @GlobalTransactional
    public Result auditAlter(String id, String remark, String status, Long uid) {
        //查询审核记录信息
        Example example = new Example(AccountAlter.class);
        example.createCriteria().andEqualTo("id", Long.parseLong(id));
        AccountAlter accountAlter = alterMapper.selectOneByExample(example);
        if (ObjectUtils.isEmpty(accountAlter) || !accountAlter.getStatus().equals("0")) {
            return new Result(true, StatusCode.ERROR, "记录信息不存在或者已审核！");
        }
        //审核人账户权限校验
        Result<User> userResult = userFeign.findUserById(uid);
        User user = userResult.getData();
        if (ObjectUtils.isEmpty(user) || "Y".equals(user.getDel().toString())) {
            return new Result(true, StatusCode.ACCESSERROR, "权限不足，审核失败！");
        }
        //校验审核的账套信息
        Result<Account> accountResult = accountFeign.findAccInfoById(accountAlter.getAcctId());
        Account account = accountResult.getData();
        if (ObjectUtils.isEmpty(account) || "N".equals(account.getStatus())) {
            return new Result(true, StatusCode.ACCESSERROR, "当前账套已失效，审核失败！");
        }
        //校验申请人的账户信息
        Result<User> applyUserResult = userFeign.findUserById(accountAlter.getUid());
        User applyUser = applyUserResult.getData();
        if (ObjectUtils.isEmpty(applyUser) || "Y".equals(applyUser.getDel())) {
            return new Result(true, StatusCode.ACCESSERROR, "被审核账户已失效，申请失败！");
        }
        accountAlter.setAlterName(user.getName());
        accountAlter.setRemarks(remark);
        accountAlter.setStatus(status);
        accountAlter.setDealDate(new Date());
        accountAlter.setIsDel("N");
        int i = alterMapper.updateByExample(accountAlter, example);
        if (i == 0) {
            return new Result(true, StatusCode.SERVER_EXCEPTION, "服务器异常！");
        }
        //当审核通过时，即status=1时，更新申请人账户信息的账套Id
        if ("1".equals(status)) {
            User upUser = new User();
            upUser.setAcctid(accountAlter.getAcctId());
            upUser.setId(accountAlter.getUid());
            Result result = userFeign.updateUserById(upUser);
            if (!result.getCode().equals(StatusCode.OK)) {
                return new Result(true, StatusCode.ERROR, "修改失败！");
            }
            //更新相关人信息
            Result personResult = personFeign.updateAcctidByUid(accountAlter.getAcctId(), accountAlter.getUid());
            if (!personResult.getCode().equals(StatusCode.OK)) {
                return new Result(true, StatusCode.ERROR, "修改失败！");
            }
        }
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @Override
    public Result findAlterList(Long acctId, String status, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        Example example = new Example(AccountAlter.class);
        example.createCriteria().andEqualTo("acctId", acctId);
        if (!ObjectUtils.isEmpty(status)) {
            example.and(example.createCriteria().andEqualTo("status", status));
        }
        example.and(example.createCriteria().andEqualTo("isDel", "N"));
        example.setOrderByClause(" id desc");
        List<AccountAlter> list = alterMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "暂无审核数据");
        }
        for (AccountAlter accountAlter : list) {
            Result<User> applyUserResult = userFeign.findUserById(accountAlter.getUid());
            User applyUser = applyUserResult.getData();
            if (!ObjectUtils.isEmpty(applyUser)) {
                accountAlter.setApplyName(applyUser.getName());
                accountAlter.setApplyAccount(applyUser.getUsername());
            }
        }
        PageInfo<AccountAlter> pageInfo = new PageInfo<AccountAlter>(list);
        return new Result(true, StatusCode.OK, "查询围栏信息成功", pageInfo);
    }

    @Override
    @GlobalTransactional
    public Result unbindAccount(Long id) {
        //查询当前账套是否绑定该UID
        Example example = new Example(AccountAlter.class);
        example.createCriteria().andEqualTo("id", id);
        example.and(example.createCriteria().andEqualTo("status", "1"));
        AccountAlter accountAlter = alterMapper.selectOneByExample(example);
        if (ObjectUtils.isEmpty(accountAlter)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "当前用户未绑定");
        }
        //校验绑定用户
        Result<User> applyUserResult = userFeign.findUserById(accountAlter.getUid());
        User applyUser = applyUserResult.getData();
        if (ObjectUtils.isEmpty(applyUser) || "Y".equals(applyUser.getDel().toString())) {
            return new Result(true, StatusCode.ACCESSERROR, "绑定账号不存在");
        }
        //变更账套
        applyUser.setAcctid(Long.parseLong("1"));
        Result result = userFeign.updateUserById(applyUser);
        if (!result.getCode().equals(StatusCode.OK)) {
            return new Result(true, StatusCode.ERROR, "解绑失败！");
        }
        //更新相关人信息
        Result personResult = personFeign.updateAcctidByUid(Long.parseLong("1"), accountAlter.getUid());
        if (!personResult.getCode().equals(StatusCode.OK)) {
            return new Result(true, StatusCode.ERROR, "解绑失败！");
        }
        //更新用户信息
        accountAlter.setIsDel("Y");
        int i = alterMapper.updateByPrimaryKey(accountAlter);
        if (i == 0) {
            return new Result(true, StatusCode.ERROR, "解绑失败！");
        }
        return new Result(true, StatusCode.OK, "解绑成功");
    }
}
